package com.zsgeek.wisdchain.qutu.view.find;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.gyf.barlibrary.ImmersionBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.zsgeek.wisdchain.qutu.R;
import com.zsgeek.wisdchain.qutu.base.customControl.EmptyRecyclerView;
import com.zsgeek.wisdchain.qutu.base.customControl.RecyclerItemDecoration;
import com.zsgeek.wisdchain.qutu.base.http.JsonRequest;
import com.zsgeek.wisdchain.qutu.base.http.JsonRequestCallBack;
import com.zsgeek.wisdchain.qutu.base.model.GetAdverListModel;
import com.zsgeek.wisdchain.qutu.base.model.GetCollectionsListModel;
import com.zsgeek.wisdchain.qutu.tools.ImageUtils;
import com.zsgeek.wisdchain.qutu.tools.TextUtils;
import com.zsgeek.wisdchain.qutu.tools.ToastHelper;
import com.zsgeek.wisdchain.qutu.tools.UrlPathHelper;
import com.zsgeek.wisdchain.qutu.view.BaseFragment;
import com.zsgeek.wisdchain.qutu.view.MainActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 推荐
 * A simple {@link Fragment} subclass.
 */
@SuppressLint("ValidFragment")
public class RecommendFragment extends BaseFragment {
    @BindView(R.id.list_date_emptyView)
    View list_date_emptyView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.recyclerView)
    EmptyRecyclerView emptyRecyclerView;

    private int newsID;
    private int pageIndex = 1, totalPage;
    private List<GetAdverListModel.DataBean> dataListBeans = new ArrayList<>();
    private String addr;

    public RecommendFragment(int id) {
        this.newsID = id;
    }

    public RecommendFragment(int id, String addr) {
        this.newsID = id;
        this.addr = addr;
    }

    @Override
    public void initImmersionBar() {
        super.initImmersionBar();
        ImmersionBar.with(this)
                .statusBarColorTransformEnable(false)
                .statusBarDarkFont(true, 0.9f)
//                .statusBarDarkFont(true, 0.2f)
                .init();
    }

    @Override
    protected int setLayoutId() {
        return R.layout.fragment_recommend;
    }

    @Override
    protected void initView(View view) {
        emptyRecyclerView.addItemDecoration(new RecyclerItemDecoration(3, 2));
        emptyRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));
        emptyRecyclerView.setEmptyView(list_date_emptyView);
        emptyRecyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                startActivityForResult(new Intent(getActivity(), FindDetailsActivity.class).putExtra("data", dataListBeans.get(position)), 0x100);
            }
        });
        initRefreshLayout();


    }

    @Override
    protected void initData() {
        refreshLayout.autoRefresh();
    }

    /**
     * 3、广告列表接口
     */
    private void getCollectionsList() {
        if (TextUtils.isEmpty(addr)) {
            new JsonRequest(new JsonRequestCallBack() {
                @Override
                public void showResult(Object object, String taskId) {
                    if (object instanceof GetAdverListModel) {
                        GetAdverListModel dataModel = (GetAdverListModel) object;
                        totalPage = dataModel.getPageQuery().getTotalPage();
                        if (dataModel.getCode() == 2000) {
                            List<GetAdverListModel.DataBean> dataBeans = dataModel.getData();
                            if (pageIndex == 1) {
                                dataListBeans.clear();
                            }
                            if (!TextUtils.isEmpty(dataBeans)) {
                                dataListBeans.addAll(dataBeans);
                            }
                            mAdapter.notifyDataSetChanged();
                        } else {
                            ToastHelper.showToast(dataModel.getMessage());
                        }
                        stopRefresh();
                    }
                }

                @Override
                public void showError(String errorMsg, String taskId) {
                    ToastHelper.showToast(errorMsg);
                    stopRefresh();
                }
            }).postJson(UrlPathHelper.getAdver() + "adver/getAdverList?partId=" + newsID
                    + "&addr=" + MainActivity.address + "&pageSize=6&pageIndex=" + pageIndex, true, null, GetAdverListModel.class);
        } else
            new JsonRequest(new JsonRequestCallBack() {
                @Override
                public void showResult(Object object, String taskId) {
                    if (object instanceof GetCollectionsListModel) {
                        GetCollectionsListModel dataModel = (GetCollectionsListModel) object;
                        totalPage = dataModel.getPageQuery().getTotalPage();
                        if (dataModel.getCode() == 2000) {
//                            List<GetCollectionsListModel.DataBean> dataBeans = dataModel.getData();
//                            if (pageIndex == 1) {
//                                dataListBeans.clear();
//                            }
//                            if (!TextUtils.isEmpty(dataBeans)) {
//                                dataListBeans.addAll(dataBeans);
//                            }
//                            mAdapter.notifyDataSetChanged();
                        } else {
                            ToastHelper.showToast(dataModel.getMessage());
                        }
                        stopRefresh();
                    }
                }

                @Override
                public void showError(String errorMsg, String taskId) {
                    ToastHelper.showToast(errorMsg);
                    stopRefresh();
                }
            }).postJson(UrlPathHelper.getAdver() + "collections/getCollectionsList?addr=" + addr + "&pageSize=6&pageIndex=" + pageIndex, true, null, GetCollectionsListModel.class);
    }


    private BaseQuickAdapter<GetAdverListModel.DataBean, BaseViewHolder> mAdapter =
            new BaseQuickAdapter<GetAdverListModel.DataBean, BaseViewHolder>(R.layout.fragment_recommend_item, dataListBeans) {
                @Override
                protected void convert(BaseViewHolder baseViewHolder, final GetAdverListModel.DataBean dataBean) {
                    baseViewHolder.setText(R.id.content_tv, dataBean.getLabel());
                    baseViewHolder.setText(R.id.nick_name_tv, dataBean.getNickName());
                    baseViewHolder.setText(R.id.love_tv, dataBean.getAgreeNum() + "");
                    ImageUtils.loadImage(getActivity(),
                            dataBean.getIsDianzan() == 2 ? R.mipmap.love_hollow_red_bg : R.mipmap.love_hollow_white_bg,
                            baseViewHolder.getView(R.id.love_iv));
                    ImageUtils.loadImage(getActivity(), dataBean.getHeadImg(), baseViewHolder.getView(R.id.title_icon_iv));

                    List<GetAdverListModel.DataBean.ImgesBean> imges = dataBean.getImges();
                    if (!TextUtils.isEmpty(imges)) {
                        ImageUtils.loadImage(getActivity(), imges.get(0).getImgUrl(), baseViewHolder.getView(R.id.avatar_iv));
                    }
                }
            };

    private void initRefreshLayout() {
        refreshLayout.setOnRefreshListener(refreshLayout -> {
            pageIndex = 1;
            getCollectionsList();
        });
        refreshLayout.setOnLoadMoreListener(refreshLayout -> {
            pageIndex++;
            getCollectionsList();
        });
    }

    private void stopRefresh() {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
        if (pageIndex >= totalPage) {
            refreshLayout.setEnableLoadMore(false);
        } else refreshLayout.setEnableLoadMore(true);
    }

}
